package com.niiwoo.civet.trade.service.local.loan.composite;

import com.alibaba.dubbo.config.annotation.Reference;
import com.niiwoo.civet.trade.enums.LoanSubmitTypeEnum;
import com.niiwoo.civet.user.service.UserForbidDubboService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @Author: wuke
 * @Description:
 * @Date: Created in 14:50 2018/5/15
 */
@Component
public class LoanServiceFactory implements ApplicationContextAware {
    @Reference(version = "1.0.0")
    private UserForbidDubboService userForbidDubboService;
    private ApplicationContext applicationContext;
    private Map<LoanSubmitTypeEnum,LoanService> LOAN_SERVICE_MAP  = new HashMap<>();

    public LoanService getLoanService(LoanSubmitTypeEnum loanSubmitTypeEnum){
        return LOAN_SERVICE_MAP.get(loanSubmitTypeEnum);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void initLoanService(){
        Optional.ofNullable(applicationContext.getBeansOfType(LoanService.class))
                .map(Map::values)
                .ifPresent(list->{
                    list.forEach(l->{
                        l.setUserForbidDubboService(userForbidDubboService);
                        LoanSubmitTypeEnum loanSubmitTypeEnum = l.getLoanSubmitMapEnum();
                        if(loanSubmitTypeEnum!=null) {
                            LOAN_SERVICE_MAP.put(loanSubmitTypeEnum, l);
                        }
                    });
                });
    }

    public Map<LoanSubmitTypeEnum, LoanService> getLOAN_SERVICE_MAP() {
        return LOAN_SERVICE_MAP;
    }
}
